import React, {Component} from 'react'
import '../style/component/SearchArea.scss'
import SearchAreaData from "./search/SearchAreaData";
import SearchAreaSearch from "./search/SearchAreaSearch";
import SearchAreaCheckbox from "./search/SearchAreaCheckbox";

const data = [
  {category: "Sporting Goods", price: "$49.99", stocked: true, name: "Football"},
  {category: "Sporting Goods", price: "$9.99", stocked: true, name: "Baseball"},
  {category: "Sporting Goods", price: "$29.99", stocked: false, name: "Basketball"},
  {category: "Electronics", price: "$99.99", stocked: true, name: "iPod Touch"},
  {category: "Electronics", price: "$399.99", stocked: false, name: "iPhone 5"},
  {category: "Electronics", price: "$199.99", stocked: true, name: "Nexus 7"}
];

/**
 * 官网search 小题目联系
 * @author leonzhangxf 20190117
 */
class SearchArea extends Component {
  constructor(props) {
    super(props);

    this.state = {
      data: data,
      search: '',
      showOnlyStock: false
    };

    this.handleSearchChange = this.handleSearchChange.bind(this);
    this.handleShowOnlyStockChange = this.handleShowOnlyStockChange.bind(this);
    this.handleCriteriaChange = this.handleCriteriaChange.bind(this);
  }

  handleSearchChange(value) {
    this.setState({
      search: value
    });
    this.handleCriteriaChange(value, this.state.showOnlyStock);
  }

  handleShowOnlyStockChange(checked) {
    this.setState({
      showOnlyStock: checked
    });
    this.handleCriteriaChange(this.state.search, checked);
  }

  /**
   * 搜索条件变化处理
   * @param search 搜索栏值
   * @param showOnlyStock 是否只显示股票
   */
  handleCriteriaChange(search, showOnlyStock) {
    if (search === '' && !showOnlyStock) {
      this.setState({
        data: data
      });
      return;
    }

    let result = data;
    if (search) {
      let searchResult = [];
      result.forEach((datum) => {
        if (datum.name.toLowerCase().indexOf(search.toLowerCase()) > -1
          || datum.category.toLowerCase().indexOf(search.toLowerCase()) > -1) {
          searchResult.push(datum);
        }
      });
      result = searchResult;
    }

    if (showOnlyStock) {
      let stockResult = [];
      result.forEach((datum) => {
        if (datum.stocked) {
          stockResult.push(datum);
        }
      });
      result = stockResult;
    }

    this.setState({
      data: result
    });
  }

  render() {
    let data = this.state.data;

    return (
      <div className="SearchArea">
        <SearchAreaSearch value={this.state.search}
                          onSearchChange={this.handleSearchChange}>
        </SearchAreaSearch>
        <br/>
        <SearchAreaCheckbox showOnlyStock={this.state.showOnlyStock}
                            onStockCheckboxChange={this.handleShowOnlyStockChange}>
        </SearchAreaCheckbox>

        <SearchAreaData data={data}>
        </SearchAreaData>
      </div>
    );
  }
}

export default SearchArea;